package org.example2;

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;

import java.io.File;
import java.io.FileOutputStream;
import java.lang.reflect.Method;

/**
 * 说明: 读取系统中已经存在的Base.class文件,并修改改文件,在process方法前后打印一句话
 *
 * 当我们执行mvn clean后,再执行mvn compile,可以看到 target/classes/org/example2
 * 目录中的Base.class是原始的class文件.只有当执行了本类中main方法,才会看到更改后的class文件.
 *
 * visitInsn : Visits a zero operand instruction.
 * visitLdcInsn : Visits a LDC instruction.  ldc加载常量 LoaD Constant
 *
 */
public class App1ModifyExistingClassByAsm {
    public static void main(String[] args) throws Exception {
        //读取
//        ClassReader classReader = new ClassReader("org/example2/Base");
        ClassReader classReader = new ClassReader("org.example2.Base");
        ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS);
        //处理
        ClassVisitor classVisitor = new MyClassVisitor(classWriter);
        classReader.accept(classVisitor, ClassReader.SKIP_DEBUG);
        byte[] data = classWriter.toByteArray();
        //输出
        File f = new File("asmTest/target/classes/org/example2/Base.class");
        FileOutputStream fout = new FileOutputStream(f);
        fout.write(data);
        fout.close();
        System.out.println("Generator rewrite target class successfully!");
    }
}
